<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
import { ref, computed, unref } from 'vue';
import { BasicModal, useModalInner } from '@/components/Modal';
import { BasicForm, useForm } from '@/components/Form/index';
import { subFormSchema } from './data';
import { useMessage } from '@/hooks/web/useMessage';
import { edit, add } from '@/api/sys/dev/sysSequenceSubManage';
const emit = defineEmits(['success']);
let isUpdate = ref(true);
const { createMessage } = useMessage();
const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
  labelWidth: 100,
  schemas: subFormSchema,
  showActionButtonGroup: false,
  baseColProps: {
    span: 24,
  },
});

const [registerModal, { setModalProps, closeModal }] = useModalInner(
  async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    console.log(data.record, 'dadada');
    setFieldsValue({
      ...data.record,
    });
  }
);
const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

async function handleSubmit() {
  try {
    const values = await validate();
    setModalProps({ confirmLoading: true });
    if (unref(isUpdate)) {
      await edit(values);
      createMessage.success('修改成功');
    } else {
      await add(values);
      createMessage.success('保存成功');
    }
    closeModal();
    emit('success');
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
</script>
